package com.aegis.common.mybatis.utils;

import com.aegis.common.mybatis.model.SortRule;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @Author renogo
 * 
 * @Version 1.0
 * @Descritube
 */
@Data
public class SortUtil implements Serializable {

    /**
     *
     * @param sort 格式 updateTime:asc,priority:desc
     * @param limitFieldMap 字段映射，如 updateTime实际对应数据库字段update_time
     * @return
     */
    public static String generateRules(String sort, Map<String, String> limitFieldMap) {
        return generateRules(parseSortRules(sort), limitFieldMap);
    }

    public static List<SortRule> parseSortRules(String sortRules) {
        List<SortRule> ruleList = new ArrayList<>();

        if (sortRules == null || sortRules.trim().isEmpty()) {
            return ruleList;
        }

        String[] rules = sortRules.split(",");
        for (String rule : rules) {
            String[] parts = rule.split(":");
            if (parts.length == 2) {
                SortRule sortRule = new SortRule();
                sortRule.setField(parts[0]);
                sortRule.setOrder(parts[1].toUpperCase(Locale.ROOT));
                ruleList.add(sortRule);
            } else {
                throw new IllegalArgumentException("非法规则 " + rule);
            }
        }
        return ruleList;
    }

    public static String generateRules(List<SortRule> sortRules, Map<String, String> limitFieldMap) {
        if (sortRules == null || sortRules.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (SortRule sortRule : sortRules) {
            String field = limitFieldMap.get(sortRule.getField());
            if (field == null) {
                throw new IllegalArgumentException("非法排序field " + field);
            }
            String order = sortRule.getOrder();
            if (order == null) {
                throw new IllegalArgumentException("非法排序order " + order);
            }
            order = order.toUpperCase(Locale.ROOT);
            if (!"DESC".equals(order) && !"ASC".equals(order)) {
                throw new IllegalArgumentException("非法排序order " + order);
            }
            sb.append(field).append(" ").append(order).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }


}
